package handler

import (
	"context"
	"mxshop-srvs/user-srvs/global"
	"mxshop-srvs/user-srvs/model"
	"mxshop-srvs/user-srvs/proto"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
)

type UserServer struct {
	// CreateUser(context.Context, *CreateUserInfo) (*UserInfoResponse, error)
	// UpdateUser(context.Context, *UpdateUserInfo) (*emptypb.Empty, error)
	// CheckPassWord(context.Context, *PasswordCheckInfo) (*CheckResponse, error)
	proto.UnimplementedUserServer
}

/**
 * @author WUKUN1549
 * @createTime 2025-01-21 17:03:43
 * @desc model转换成proto定义的UserInfoResponse
 */
func ModelToResponse(user model.User) proto.UserInfoResponse {
	userInfoRsp := proto.UserInfoResponse{
		Id:       user.ID,
		PassWord: user.Password,
		NickName: user.NickName,
		Gender:   user.Gender,
		Role:     int32(user.Role),
		Mobile:   user.Mobile,
	}
	if user.Birthday != nil {
		userInfoRsp.BirthDay = uint64(user.Birthday.Unix())
	}
	return userInfoRsp
}

/**
 * @author WUKUN1549
 * @createTime 2025-01-21 16:55:16
 * @desc 分页函数
 */
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

/**
 * @author WUKUN1549
 * @createTime 2025-01-21 16:43:32
 * @desc 获取用户列表
 */
func (s *UserServer) GetUserList(ctx context.Context, pInfo *proto.PageInfo) (*proto.UserListResponse, error) {
	var users []model.User
	result := global.DB.Find(&users)
	if result.Error != nil {
		return nil, result.Error
	}
	rsp := &proto.UserListResponse{}
	rsp.Total = int32(result.RowsAffected)

	global.DB.Scopes(Paginate(int(pInfo.Pn), int(pInfo.PSize))).Find(&users)

	for _, user := range users {
		userInfoRsp := ModelToResponse(user)
		rsp.Data = append(rsp.Data, &userInfoRsp)
	}

	return rsp, nil
}

/**
 * @author WUKUN1549
 * @createTime 2025-01-23 14:40:25
 * @desc 通过手机号获取用户信息
 */
func (s *UserServer) GetUserByMobile(ctx context.Context, mReq *proto.MobileRequest) (*proto.UserInfoResponse, error) {
	var user model.User
	result := global.DB.Where(&model.User{Mobile: mReq.Mobile}).First(&user)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	if result.Error != nil {
		return nil, result.Error
	}

	rsp := ModelToResponse(user)

	return &rsp, nil
}

/**
 * @author WUKUN1549
 * @createTime 2025-01-23 14:40:44
 * @desc 通过id获取用户信息
 */
func (s *UserServer) GetUserById(ctx context.Context, req *proto.IdRequest) (*proto.UserInfoResponse, error) {
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	if result.Error != nil {
		return nil, result.Error
	}

	rsp := ModelToResponse(user)
	return &rsp, nil
}
